<template>
  <div class="app-container">
    <!-- 顶部搜索 -->
    <el-form :model="queryParams" ref="queryForm" size="small" v-show="showSearch" label-width="80px">
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="项目名称:" prop="xmName">
            <el-input
              v-model="queryParams.xmName"
              placeholder="请输入项目名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="项目编号:" prop="xmBh">
            <el-input
              v-model="queryParams.xmBh"
              placeholder="请输入项目编号"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="承担单位:" prop="cdDw">
            <el-input
              v-model="queryParams.cdDw"
              placeholder="请输入承担单位"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="8">
          <el-form-item label="流程状态:" prop="processStatus">
            <el-select v-model="queryParams.processStatus" placeholder="请选择流程状态" clearable>
              <el-option
                v-for="dict in dict.type.jjkc_lczt"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="鉴定年度:" prop="jdNd">
            <el-select v-model="queryParams.jdNd" placeholder="请选择鉴定年度" clearable>
              <el-option
                v-for="dict in dict.type.year"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 顶部按钮 -->
    <el-form :model="queryParams" size="mini" label-width="170px">
      <el-row :gutter="10" class="mb8">
<!--        <el-col :span="1.5">-->
<!--          <el-button-->
<!--            type="primary"-->
<!--            icon="el-icon-plus"-->
<!--            size="mini"-->
<!--            @click="handleAdd"-->
<!--            v-hasPermi="['jjkc:jjkcsq:add']"-->
<!--          >新增-->
<!--          </el-button>-->
<!--        </el-col>-->
<!--        <el-col :span="1.5">-->
<!--          <el-button-->
<!--            type="primary"-->
<!--            icon="el-icon-edit"-->
<!--            size="mini"-->
<!--            :disabled="!selectedRow || (selectedRow.processStatus !== 1 && selectedRow.processStatus !== 4)"-->
<!--            @click="handleUpdate"-->
<!--            v-hasPermi="['jjkc:jjkcsq:edit']"-->
<!--          >修改-->
<!--          </el-button>-->
<!--        </el-col>-->
<!--        <el-col :span="1.5">-->
<!--          <el-button-->
<!--            type="primary"-->
<!--            icon="el-icon-delete"-->
<!--            size="mini"-->
<!--            :disabled="!selectedRow || (selectedRow.processStatus !== 1 && selectedRow.processStatus !== 4)"-->
<!--            @click="handleDelete"-->
<!--            v-hasPermi="['jjkc:jjkcsq:remove']"-->
<!--          >删除-->
<!--          </el-button>-->
<!--        </el-col>-->
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['jjkc:jjkcsq:export']"
          >导出
          </el-button>
        </el-col>
<!--        <el-col :span="1.5">-->
<!--          <el-button-->
<!--            type="primary"-->
<!--            icon="el-icon-edit"-->
<!--            size="mini"-->
<!--            :disabled="!selectedRow || (selectedRow.processStatus !== 1 && selectedRow.processStatus !== 4)"-->
<!--            @click="handleStartTask"-->
<!--          >发起申请-->
<!--          </el-button>-->
<!--        </el-col>-->
<!--        <el-col :span="1.5">-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="primary"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleRevokeProcess"-->
<!--            :disabled="!selectedRow || selectedRow.processStatus !== 2"-->
<!--          >撤销流程-->
<!--          </el-button>-->
<!--        </el-col>-->
<!--        <el-col :span="1.5" style="margin-left: auto;">-->
<!--          <el-form-item label="加计扣除鉴定计划:" prop="jdNd">-->
<!--            <vxe-select @change="getList" size="mini" v-model="queryParams.jdNd" placeholder="请选择加计扣除鉴定计划">-->
<!--              <vxe-option v-for="dict in dict.type.year" :key="dict.value" :value="dict.value"-->
<!--                          :label="dict.label + '年加计扣除活动'"></vxe-option>-->
<!--            </vxe-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
    </el-form>

    <!-- 表格 -->
    <el-table @row-click="clickRow" ref="table" highlight-current-row
              :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
              height="300" class="fixedTableOne" v-loading="loading" :data="jjkcsqList"
              @selection-change="handleSelectionChange">
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="序号" align="center" type="index" :index="indexMethod"/>
      <el-table-column show-overflow-tooltip label="鉴定年度" align="center" prop="jdNd" width="80">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.year" :value="scope.row.jdNd"/>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="项目名称" align="center" prop="xmName">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="handleButtonClick(scope.row)"
          >
            <el-link type="primary">{{ scope.row.xmName }}</el-link>
          </el-button>
        </template>
      </el-table-column>
      <el-table-column show-overflow-tooltip label="项目编号" align="center" prop="xmBh"/>
      <el-table-column show-overflow-tooltip label="课题归属" align="center" prop="ktGs"/>
      <el-table-column show-overflow-tooltip label="行业分类" align="center" prop="hyFl"/>
      <el-table-column show-overflow-tooltip label="承担单位" align="center" prop="cdDw"/>
      <el-table-column show-overflow-tooltip label="研究总经费(万元)" align="center" prop="yjZjf"/>
      <el-table-column show-overflow-tooltip label="当年发生额(元)" align="center" prop="bndFse"/>
      <el-table-column label="状态" align="center" prop="processStatus" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.jjkc_lczt" :value="scope.row.processStatus" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--            v-if="scope.row.processStatus==1 || scope.row.processStatus==4"-->
<!--          >修改-->
<!--          </el-button>-->
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-if="scope.row.processStatus==1 || scope.row.processStatus==4"-->
<!--          >删除-->
<!--          </el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleJinDu(scope.row)"
            v-if="scope.row.processStatus !== 1"
          >查询进度
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改加计扣除申请对话框 -->
    <vxe-modal :title="title" v-model="open" width="79%" showFooter show-zoom resize>
      <el-form ref="formDialog" :model="form" :rules="rules" label-width="170px">
        <el-tabs type="border-card" v-model="activeName">
          <!-- 基本资料 -->
          <el-tab-pane name="jbzl" :lazy=true>
            <span slot="label"><i class="el-icon-date"></i> 基本资料</span>
            <div v-if="activeName === 'jbzl'" style="height: 72vh; overflow-y: auto;">
              <el-card class="box-card">
                <div slot="header" class="clearfix" style="text-align: center;">
                  <span style="font-size: 20px; color: #1890ff">基本资料</span>
                </div>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="项目名称" prop="xmName">
                      <el-input v-model="form.xmName" placeholder="请输入项目名称" class="custom-input"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目编号" prop="xmBh">
                      <el-input v-model="form.xmBh" placeholder="请输入项目编号" class="custom-input"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="行业分类" prop="hyFl">
                      <el-input v-model="form.hyFl" placeholder="请输入行业分类"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="课题归属" prop="ktGs">
                      <el-input v-model="form.ktGs" placeholder="请输入课题归属" class="custom-input"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="研究总经费(万元)" prop="yjZjf">
                      <el-input v-model="form.yjZjf" placeholder="请输入研究总经费(万元)"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="本年度发生额(元)" prop="bndFse">
                      <el-input v-model="form.bndFse" placeholder="请输入本年度发生额(元)"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="鉴定年度" prop="jdNd">
                      <el-select v-model="form.jdNd" placeholder="请选择鉴定年度">
                        <el-option
                          v-for="dict in dict.type.year"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="承担单位" prop="cdDw">
                      <el-input v-model="form.cdDw" placeholder="请输入承担单位"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="项目负责人" prop="xmFzName">
                      <el-input v-model="form.xmFzName" placeholder="请输入项目负责人"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="联系电话" prop="lxPhone">
                      <el-input v-model="form.lxPhone" placeholder="请输入联系电话"/>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-card>
            </div>
          </el-tab-pane>

          <!-- 技术资料目录 -->
          <el-tab-pane name="jsZlMl" :lazy=true>
            <span slot="label"><i class="el-icon-date"></i> 技术资料目录</span>
            <div v-if="activeName === 'jsZlMl'" style="height: 72vh; overflow-y: auto;">
              <el-card class="box-card">
                <div slot="header" class="clearfix" style="text-align: center;">
                  <span style="font-size: 20px; color: #1890ff">技术资料目录</span>
                </div>
                <el-row :gutter="20">
                  <el-col :span="6" :xs="24">
                    <div class="head-container">
                      <el-tree
                        :data="fileOptions"
                        :props="defaultProps"
                        :expand-on-click-node="false"
                        :filter-node-method="filterNode"
                        ref="tree"
                        node-key="id"
                        default-expand-all
                        highlight-current
                        @node-click="handleNodeClick"
                        :render-content="renderContent"
                      />
                    </div>
                  </el-col>
                  <el-col :span="18" :xs="24">
                    <el-row :gutter="10" class="mb8">
                      <el-col :span="1.5">
                        <!-- 上传按钮 -->
                        <el-button size="mini" icon="el-icon-upload" type="primary" @click="jjkcsqFileUpload">上传
                        </el-button>
                      </el-col>
                      <el-col :span="1.5">
                        <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteJjkcsqFj">删除
                        </el-button>
                      </el-col>
                      <el-col :span="1.5">
                        <el-button type="success" icon="el-icon-download" sizi="mini" @click="handleDownloadAll">全部下载
                        </el-button>
                      </el-col>
                    </el-row>
                    <el-table v-loading="loadingFj"
                              :header-cell-style="{background:'#d0cece',color:'#000000',fontWeight:'bold'}"
                              :data="jjkcsqFjList" :row-class-name="rowJjkcsqFjIndex" height="58vh"
                              @selection-change="handleJjkcsqFjSelectionChange" ref="jjkcsqFj">
                      <el-table-column type="selection" width="50" align="center"/>
                      <el-table-column label="序号" align="center" prop="index" width="50"/>
                      <el-table-column show-overflow-tooltip label="文件类型" align="center" prop="fileType"/>
                      <el-table-column show-overflow-tooltip label="文件名称" align="center" prop="fileName"
                                       :formatter="getFileNames"/>
                      <el-table-column show-overflow-tooltip label="文件大小" align="center" prop="fileSize"/>
                      <el-table-column width="120" align="center" label="操作" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                          <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-view"
                            @click="handlePreview(scope.row)"
                          >预览
                          </el-button>
                          <el-button
                            size="mini"
                            type="text"
                            icon="el-icon-edit"
                            @click="handleDownload(scope.row)"
                          >下载
                          </el-button>
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-col>
                </el-row>
              </el-card>
            </div>
          </el-tab-pane>

          <!-- 企业研究开发项目情况表 -->
          <el-tab-pane name="qyYjKfXmQkb" :lazy=true>
            <span slot="label"><i class="el-icon-date"></i> 企业研究开发项目情况表</span>
            <div v-if="activeName === 'qyYjKfXmQkb'" style="height: 72vh; overflow-y: auto;">
              <el-card class="box-card">
                <div slot="header" class="clearfix" style="text-align: center;">
                  <span style="font-size: 20px; color: #1890ff">一、企业基本信息</span>
                </div>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="企业名称(盖章)" prop="qyName">
                      <el-input disabled v-model="form.qyName" placeholder="请输入企业名称(盖章)"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="法人代表" prop="frDb">
                      <el-input disabled v-model="form.frDb" placeholder="请输入法人代表"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="通讯地址" prop="txDz">
                      <el-input disabled v-model="form.txDz" placeholder="请输入通讯地址"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="企业联系电话(座机)" prop="qyLxDh">
                      <el-input disabled v-model="form.qyLxDh" placeholder="请输入企业联系电话(座机)"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="企业所属国民经济行业" prop="qySsGmjjHy">
                      <el-input disabled v-model="form.qySsGmjjHy" placeholder="请输入企业所属国民经济行业"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="企业类型" prop="qyLx">
                      <el-input disabled v-model="form.qyLx" placeholder="请输入企业类型"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="职工总人数" prop="zgZrs">
                      <el-input disabled v-model="form.zgZrs" placeholder="请输入职工总人数"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="研发人员数" prop="yfRys">
                      <el-input disabled v-model="form.yfRys" placeholder="请输入研发人员数"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="年度销售收入(万元)" prop="ndXsSr">
                      <el-input disabled v-model="form.ndXsSr" placeholder="请输入年度销售收入(万元)"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="年度利税(万元)" prop="ndLs">
                      <el-input disabled v-model="form.ndLs" placeholder="请输入年度利税(万元)"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="联系人" prop="lxr">
                      <el-input disabled v-model="form.lxr" placeholder="请输入联系人"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="联系电话" prop="lxDh">
                      <el-input disabled v-model="form.lxDh" placeholder="请输入联系电话"/>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-card>
              <el-card class="box-card">
                <div slot="header" class="clearfix" style="text-align: center;">
                  <span style="font-size: 20px; color: #1890ff">二、研发项目情况</span>
                </div>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="项目名称" prop="xmName">
                      <el-input disabled v-model="form.xmName" placeholder="请输入项目名称"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目编号" prop="xmBh">
                      <el-input disabled v-model="form.xmBh" placeholder="请输入项目编号"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="项目有效期限" prop="xmYxQx">
                      <el-input v-model="form.xmYxQx" placeholder="请输入项目有效期限"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="总经费" prop="zjf">
                      <el-input v-model="form.zjf" placeholder="请输入总经费"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="企业自筹金额" prop="qyZcJe">
                      <el-input v-model="form.qyZcJe" placeholder="请输入企业自筹金额"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="银行贷款" prop="yhDk">
                      <el-input v-model="form.yhDk" placeholder="请输入银行贷款"/>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="上年度研发费实际发生额" prop="sndYffSjfs">
                      <el-input disabled v-model="form.sndYffSjfs" placeholder="请输入上年度研发费实际发生额"/>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="项目开发形式" prop="xmKfXs">
                      <el-select v-model="form.xmKfXs" placeholder="请选择项目开发形式">
                        <el-option
                          v-for="dict in dict.type.jjkc_xmkfxs"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row :gutter="24">
                  <el-col :span="12">
                    <el-form-item label="项目目前所处阶段" prop="xmMqScJd">
                      <el-select v-model="form.xmMqScJd" placeholder="请选择项目目前所处阶段">
                        <el-option
                          v-for="dict in dict.type.jjkc_xmmqscjd"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="研发活动类型" prop="yfHdLx">
                      <el-select v-model="form.yfHdLx" placeholder="请选择研发活动类型">
                        <el-option
                          v-for="dict in dict.type.jjkc_yfhdlx"
                          :key="dict.value"
                          :label="dict.label"
                          :value="dict.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-card>
              <el-card class="box-card">
                <div slot="header" class="clearfix" style="text-align: center;">
                  <span style="font-size: 20px; color: #1890ff">三、项目主要研究内容</span>
                </div>
                <el-form-item label="1、目的及组织方式:">
                  <editor v-model="form.mdJZzfs" :height="300"/>
                </el-form-item>
                <el-form-item label="2、核心技术及创新点:">
                  <editor v-model="form.hxjsJCxd" :height="300"/>
                </el-form-item>
                <el-form-item label="3、取得成果:">
                  <editor v-model="form.qdCg" :height="300"/>
                </el-form-item>
              </el-card>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </vxe-modal>

    <!-- 加计扣除项目选择 -->
    <JjkcXmDx ref="jjkcXmDx"/>

    <!-- 加计扣除申请附件上传弹窗 -->
    <vxe-modal title="附件上传" v-model="fjUpload" width="25%" showFooter show-zoom resize @close="fjClose">
      <el-upload
        align="center"
        class="upload-demo"
        multiple
        :action="uploadFileUrl"
        :before-upload="handleBeforeUpload"
        :file-list="fileList"
        :limit="20"
        :on-error="handleUploadError"
        :on-exceed="handleExceed"
        :on-success="handleUploadSuccess"
        :headers="headers"
        ref="fileUpload"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">
          请上传
          <template> 大小不超过 <b style="color: #f56c6c">{{ 50 }}MB</b></template>
          <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b></template>
          的文件
        </div>
      </el-upload>

      <div slot="footer" class="dialog-footer" style="display: flex; justify-content: center;">
        <el-button v-if="allFilesUploaded === false" size="mini" type="primary" @click="fjUpload = false">关 闭
        </el-button>
        <el-button v-if="allFilesUploaded === true" size="mini" type="primary" @click="fjClose">上传完成, 关闭
        </el-button>
      </div>

    </vxe-modal>

    <!-- 预览组件 -->
    <KkFileView ref="preview"/>

    <!-- 加计扣除申请详情 -->
    <JjKcSqXq ref="jjKcSqXq"/>

    <!-- 查询进度 -->
    <Jindu ref="picture"/>
  </div>
</template>

<script>
import {
  addJjkcsq,
  deleteJjkcsqFjByFjIds,
  delJjkcsq,
  getJjkcsq,
  insertJjkcsqFjByJjkcsqId,
  listJjkcsq,
  selectJjkcsqFjList,
  updateJjkcsq
} from "@/api/jjkc/jjkcsq";
import JjkcXmDx from "@/views/components/jjkcXmXz/JjkcXmDx.vue";
import {getToken} from "@/utils/auth";
import KkFileView from "@/views/components/KKFileView/kkFileView.vue";
import JjKcSqXq from "@/views/jjkc/jjkcsq/components/JjKcSqXq.vue";
import Jindu from "@/views/components/liuChengState/jindu.vue";
import {revokeProcess, startTask} from "@/api/activiti/task";
import JSZip from 'jszip';
import {saveAs} from 'file-saver';

export default {
  name: "JjKcCx", //加计扣除查询页面
  components: {Jindu, JjKcSqXq, KkFileView, JjkcXmDx},
  dicts: ['jjkc_xmkfxs', 'jjkc_xmmqscjd', 'year', 'jjkc_yfhdlx', 'jjkc_lczt'],
  provide() {
    return {
      updateJjkcXmLabel: (val) => {
        let form = {
          jjkcsqId: null,
          xmName: val.xmName,
          xmBh: val.xmBh,
          ktGs: val.ktGs,
          yjZjf: val.xmZjf,
          bndFse: val.dnFse,
          jdNd: val.nd,
          cdDw: val.cdDw,
          xmFzName: val.xmFzName,
          lxPhone: val.lxDh,
          xmYxQx: val.qTime + '至' + val.zTime,
          zjf: val.xmZjf,
          qyZcJe: val.zcJe,
          sndYffSjfs: val.dnFse,
          xmsbId: val.xmsbId,
          jdjhId: val.jdjhId,
        };
        addJjkcsq(form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.getList();
        });
      },
    };
  },
  data() {
    return {
      fileOptions: [{ //附件类型树表
        id: 1,
        label: '1.企业研究开发项目情况表(word)',
        type: '企业研究开发项目情况表'
      }, {
        id: 2,
        label: '2.研发开发计划任务书(word)',
        type: '研发开发计划任务书'
      }, {
        id: 3,
        label: '3.项目组的编制情况和研发人员名单(word)',
        type: '项目组的编制情况和研发人员名单'
      }, {
        id: 4,
        label: '4.立项决议文件(pdf)',
        type: '立项决议文件'
      }, {
        id: 5,
        label: '5.研究开发项目的合同(pdf)',
        type: '研究开发项目的合同',
        children: [{
          id: 6,
          label: '5.1合同变更',
          type: '合同变更',
        }]
      }, {
        id: 7,
        label: '6.研究成果报告(word)',
        type: '研究成果报告'
      }, {
        id: 8,
        label: '7.其他证明(jpg,pdf)',
        type: '其他证明'
      }, {
        id: 9,
        label: '8.归集表(word,pdf,excel)',
        type: '归集表'
      }],
      jjkcsqFileType: "企业研究开发项目情况表", //默认的附件类型
      defaultProps: {children: "children", label: "label"}, // 表单参数
      xg: false, //判断是新增还是修改 (false新增 true修改)
      allFilesUploaded: false, // 添加这个来追踪所有文件是否上传完成
      fjUpload: false, //附件上传弹窗
      //要修改的 加计扣除申请id
      jjkcsqIdEdit: "",
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload", // 上传文件服务器地址
      fileList: [],
      headers: {Authorization: "Bearer " + getToken()},
      number: 0,
      uploadList: [],
      fileType: ["doc", "xls", "ppt", "txt", "pdf", "docx", "zip"],
      activeName: 'jbzl', //初始打开的标签页
      selectedRow: null, // 保存当前选中的行
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedJjkcsqFj: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 加计扣除申请表格数据
      jjkcsqList: [],
      // 加计扣除申请附件表格数据
      jjkcsqFjList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        xmName: null,
        xmBh: null,
        jdNd: null,
        cdDw: null,
        idWhere: null,
        userId: null,
        deptId: null,
        processStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        xmName: [{required: true, message: "项目名称不能为空", trigger: "blur"}],
        xmBh: [{required: true, message: "项目编号不能为空", trigger: "blur"}],
        ktGs: [{required: true, message: "课题归属不能为空", trigger: "blur"}],
        jdNd: [{required: true, message: "鉴定年度不能为空", trigger: "change"}],
      },
      loadingFj: false,
    };
  },
  created() {
    this.getList();
  },
  watch: {
    activeName(newVal) {
      if (newVal === 'jsZlMl') {
        this.clickFirstNode();
      }
    },
  },
  mounted() {
    if (this.activeName === 'jsZlMl') {
      this.clickFirstNode();
    }
  },
  methods: {
    // 附件打包下载
    async handleDownloadAll() {
      const zip = new JSZip()

      getJjkcsq(this.jjkcsqIdEdit).then(async res => {
        console.log(res)
        const fileList = res.data.jjkcsqFjList
        if (fileList.length === 0) {
          this.$modal.alertWarning('没有相关附件, 请先上传文件')
        } else {
          // 打开遮罩层
          this.$modal.loading('正在打包文件，请稍后...')
          for (let i = 0; i < fileList.length; i++) {
            const file = fileList[i]
            const fileName = file.fileName
            const finalFileName = fileName.substring(fileName.lastIndexOf('/') + 1)

            const fileResponse = await fetch(`/dev-api${fileName}`)
            const blob = await fileResponse.blob()
            zip.file(finalFileName, blob)
          }
          const content = await zip.generateAsync({type: 'blob'})
          saveAs(content, `${res.data.xmName}-${res.data.xmBh}_(附件).zip`)
          this.$modal.closeLoading()// 关闭遮罩层
        }
      })
    },
    //发起任务
    handleStartTask() {
      const row = this.selectedRow; // 获取当前选中的行
      if (!row) {
        this.$message.error("请先选择一行数据");
        return;
      }
      this.$confirm("是否确认发起申请？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$modal.loading("正在发起申请，请稍后...");
          startTask({businessKey: row.jjkcsqId, businessType: 13}).then(res => {
            this.getList();
            this.$modal.msgSuccess("发起成功");
            this.selectedRow = null
            // 关闭遮罩层
            this.$modal.closeLoading();
          });
        })
        .catch(() => {
        });
    },
    //撤销流程
    handleRevokeProcess() {
      const row = this.selectedRow; // 获取当前选中的行
      if (!row) {
        this.$message.error("请先选择一行数据");
        return;
      }
      this.$confirm("是否确撤销申请？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$modal.loading("正在撤销申请，请稍后...");
          let params = {
            businessKey: row.jjkcsqId,
            businessType: 13,
            processInstanceId: row.processInstanceId
          };
          revokeProcess(params).then(res => {
            this.getList();
            this.$modal.msgSuccess("撤销成功");
            this.selectedRow = null
            // 关闭遮罩层
            this.$modal.closeLoading();
          });
        })
        .catch(() => {
        });
    },
    //查询进度
    handleJinDu(row) {
      this.$refs.picture.handleOpen(row);
    },
    //打开加计扣除申请申请详情
    handleButtonClick(row) {
      this.$refs.jjKcSqXq.handleOpen(row);
    },
    clickFirstNode() {
      this.$nextTick(() => {
        const firstNode = this.$refs.tree.store.nodesMap['1']; // 默认点击id为1的节点
        if (firstNode) {
          this.$refs.tree.setCurrentKey(firstNode.key);
          this.handleNodeClicks(firstNode.data);
        }
      });
    },
    handleNodeClicks(data) {
      this.loadingFj = true
      let jjkcsqId = null
      jjkcsqId = this.jjkcsqIdEdit
      this.jjkcsqFileType = data.type
      selectJjkcsqFjList(jjkcsqId, this.jjkcsqFileType).then(resFileList => {
        this.jjkcsqFjList = resFileList.data;
        this.loadingFj = false
      })
    },
    // 节点单击事件
    handleNodeClick(data, node) {
      this.loadingFj = true
      let jjkcsqId = null
      jjkcsqId = this.jjkcsqIdEdit
      //根据附件类型查询附件列表
      this.jjkcsqFileType = data.type
      selectJjkcsqFjList(jjkcsqId, this.jjkcsqFileType).then(resFileList => {
        console.log(resFileList, 'asdasd')
        this.jjkcsqFjList = resFileList.data;
        this.loadingFj = false
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 打开预览组件
    handlePreview(row) {
      this.$refs.preview.handleOpen(row);
    },
    // 文件下载处理
    handleDownload(row) {
      const resource = row.fileName;
      // 默认方法
      this.$download.resource(resource);
    },
    // 获取文件名原名
    getFileNames(row) {
      // 从路径中提取文件名
      return row.fileName.split('/').pop(); // 返回文件名部分
    },
    //关闭上传附件弹窗后
    fjClose() {
      this.fileList = []
      this.allFilesUploaded = false
      this.fjUpload = false
    },
    //上传文件之前的钩子
    handleBeforeUpload(file) {
      let that = this;
      // 校检文件类型
      if (this.fileType) {
        const fileName = file.name.split('.');
        const fileExt = fileName[fileName.length - 1];
        const isTypeOk = this.fileType.indexOf(fileExt) >= 0;
        if (!isTypeOk) {
          this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false;
        }
        // 校检文件大小
        if (this.fileSize) {
          const isLt = file.size / 1024 / 1024 < this.fileSize;
          if (!isLt) {
            this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB!`);
            return false;
          }
        }
        this.$modal.loading("正在上传文件，请稍候...");
        this.number++;
        return true;
      }
    },
    // 对象转成指定字符串分隔
    listToString(list, separator) {
      let strs = "";
      separator = separator || ",";
      for (let i in list) {
        strs += list[i].url + separator;
      }
      return strs !== '' ? strs.substr(0, strs.length - 1) : '';
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传文件失败，请重试");
      this.$modal.closeLoading();
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传成功
    handleUploadSuccess(res, file) {
      let that = this;
      if (res.code === 200) {
        this.uploadList.push({name: res.fileName, url: res.fileName, size: that.formatFileSize(file.size)});
        let xgItemFile = {
          "jjkcsqId": that.jjkcsqIdEdit,
          "fileType": that.jjkcsqFileType,
          "fileName": res.fileName,
          "fileSize": that.formatFileSize(file.size)
        };
        // 点击修改按钮的上传
        insertJjkcsqFjByJjkcsqId(xgItemFile).then(resFil => {
          that.getJjkcsqFjList();
        })
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.fileUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
      this.allFilesUploaded = true
      this.$modal.msgSuccess("上传成功")
      // this.fjShangChuan = false
    },
    getJjkcsqFjList() {
      let that = this;
      //点击修改 上传文件后的文件列表
      selectJjkcsqFjList(that.jjkcsqIdEdit, that.jjkcsqFileType).then(resFileList => {
        that.jjkcsqFjList = resFileList.data;
      })
    },
    // 显示文件大小为KB, MB, GB, TB
    formatFileSize(size) {
      if (size === 0) return '0 Bytes';
      const k = 1024;
      const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
      const i = Math.floor(Math.log(size) / Math.log(k));
      return parseFloat((size / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    },
    // 获取文件名称
    getFileName(name) {
      // 如果是url那么取最后的名字 如果不是直接返回
      if (name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return name;
      }
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.fileList = this.fileList.map(item => {
          // 使用split方法去除name中的特定前缀
          item.name = item.name.split('/').pop();
          return item;
        });
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", this.listToString(this.fileList));
        this.$modal.closeLoading();
      }
    },
    //加计扣除附件上传按钮
    jjkcsqFileUpload() {
      this.fjUpload = true;
    },
    //点击行 获取行
    clickRow(row) {
      this.selectedRow = row; // 更新选中的行
      const table = this.$refs.table;
      const selectedRows = table.selection;

      // 否则取消之前选中的行，并选中当前点击的行
      selectedRows.forEach(selectedRow => {
        table.toggleRowSelection(selectedRow);
      });
      table.toggleRowSelection(row);
    },
    /** 自定义序号 */
    indexMethod(index) {
      let pageNum = this.queryParams.pageNum - 1;
      if ((pageNum !== -1 && pageNum !== 0)) {
        return (index + 1) + (pageNum * this.queryParams.pageSize);
      } else {
        return (index + 1)
      }
    },
    /** 查询加计扣除申请列表 */
    getList() {
      this.loading = true;
      listJjkcsq(this.queryParams).then(response => {
        this.jjkcsqList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        jjkcsqId: null,
        xmName: null,
        xmBh: null,
        hyFl: null,
        ktGs: null,
        yjZjf: null,
        bndFse: null,
        jdNd: null,
        cdDw: null,
        xmFzName: null,
        lxPhone: null,
        qyName: null,
        frDb: null,
        txDz: null,
        qyLxDh: null,
        qySsGmjjHy: null,
        qyLx: null,
        zgZrs: null,
        yfRys: null,
        ndXsSr: null,
        ndLs: null,
        lxr: null,
        lxDh: null,
        xmYxQx: null,
        zjf: null,
        qyZcJe: null,
        yhDk: null,
        sndYffSjfs: null,
        xmKfXs: null,
        xmMqScJd: null,
        yfHdLx: null,
        mdJZzfs: null,
        hxjsJCxd: null,
        qdCg: null,
        idWhere: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        userId: null,
        deptId: null,
        xmsbId: null,
      };
      this.jjkcsqFjList = [];
      this.resetForm("formDialog");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      let ids = selection.map(item => item.jjkcsqId)
      if (ids.length === 1) {
        this.ids = ids[0]
      } else {
        this.ids = ids
      }
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.xg = false
      this.$refs.jjkcXmDx.handleOpen(this.queryParams.jdNd)
      // this.reset();
      // this.activeName = 'jbzl'
      // this.open = true;
      // this.title = "添加加计扣除申请";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // this.reset();
      this.xg = true
      const jjkcsqId = row.jjkcsqId || this.ids
      this.jjkcsqIdEdit = row.jjkcsqId || this.ids
      getJjkcsq(jjkcsqId).then(response => {
        this.form = response.data;
        selectJjkcsqFjList(jjkcsqId, this.jjkcsqFileType).then(res => {
          this.jjkcsqFjList = res.data
          this.activeName = 'jbzl'
          this.open = true;
          this.title = "修改加计扣除申请";
        })
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["formDialog"].validate(valid => {
        if (valid) {
          this.form.jjkcsqFjList = this.jjkcsqFjList;
          updateJjkcsq(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
            this.xg = false
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const jjkcsqIds = row.jjkcsqId || this.ids;
      this.$modal.confirm('确定删除选中记录？').then(function () {
        return delJjkcsq(jjkcsqIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 加计扣除申请附件序号 */
    rowJjkcsqFjIndex({row, rowIndex}) {
      row.index = rowIndex + 1;
    },
    /** 加计扣除申请附件删除按钮操作 */
    handleDeleteJjkcsqFj() {
      if (this.checkedJjkcsqFj.length == 0) {
        this.$modal.msgError("请先选择要删除的加计扣除申请附件数据");
      } else {
        const fjIds = this.checkedJjkcsqFj;
        this.$modal.confirm('确定删除选中记录？').then(function () {
          return deleteJjkcsqFjByFjIds(fjIds);
        }).then(() => {
          selectJjkcsqFjList(this.jjkcsqIdEdit, this.jjkcsqFileType).then(response => {
            this.jjkcsqFjList = response.data.jjkcsqFjList;
          });
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {
        });
      }
    },
    /** 复选框选中数据 */
    handleJjkcsqFjSelectionChange(selection) {
      this.checkedJjkcsqFj = selection.map(item => item.fjId)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('jjkc/jjkcsq/export', {
        ...this.queryParams
      }, `jjkcsq_${new Date().getTime()}.xlsx`)
    },
  }
};
</script>

<style scoped>
.custom-input ::v-deep .el-input__inner {
  background-color: #ffffe6;
}
</style>
